package cn.liumouren.tool.security.core;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.Ordered;
import org.springframework.util.Assert;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

/**
 * 选择{@link WebMvcConfigurer}而不选择{@link WebMvcConfigurationSupport}的原因
 *
 * <p>实现{@link WebMvcConfigurationSupport}会使{@link org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration}失效
 *
 * <p>{@code @Order}、{@code Ordered}不影响类的加载顺序, 只影响执行顺序
 *
 * @author Daniel Liu
 * @date 2021/3/10 21:41
 */
public abstract class DlInterceptor implements HandlerInterceptor, Ordered, InitializingBean {
    /**
     * 拦截器作用的 urlPatterns
     */
    private final Set<String> urlPatterns = new HashSet<>();
    /**
     * 拦截器排除的 urlPatterns
     */
    private final Set<String> excludePatterns = new HashSet<>();
    /**
     * order越小优先级越高
     */
    private int order = 0;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }

    public final DlInterceptor addPatterns(String... urlPatterns) {
        Assert.notNull(urlPatterns, "urlPatterns not null.");
        this.urlPatterns.addAll(Arrays.asList(urlPatterns));
        return this;
    }

    public final DlInterceptor excludePatterns(String... urlPatterns) {
        Assert.notNull(urlPatterns, "urlPatterns not null.");
        this.excludePatterns.addAll(Arrays.asList(urlPatterns));
        return this;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
    }

    @Override
    public final int getOrder() {
        return order;
    }

    public final void setOrder(int order) {
        this.order = order;
    }

    public final Set<String> getUrlPatterns() {
        return urlPatterns;
    }

    public final Set<String> getExcludePatterns() {
        return excludePatterns;
    }
}
